import React, { useEffect, useState } from 'react'
import MyHead from '../../components/MyHead'
import { useSelector, useDispatch } from 'react-redux';
import { changeCartList, getCartListAsync, getUserInfoAsync } from '../../rtk/modules/data';
import { Button, Empty, List, Image, Ellipsis, Checkbox, Stepper, SwipeAction, Dialog } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { Ajax } from '../../api/api';
import { ShowMsg } from '../../utils/message';
import './index.scss'


const Cart = () => {
    const router = useNavigate()
    let cartList = useSelector((state: any) => state.data.cartList)
    const dispatch = useDispatch() as any;
    const userInfo = useSelector((state: any) => state.data.userInfo)
    const [value, setValue] = useState<any>(1)
    const [quan, setQuan] = useState<boolean>(false)
    const [total, setTotal] = useState<number>(0)
    const [allCount, setAllCount] = useState<number>(0)
    const changeCount = (value: any) => {
    }

    useEffect(() => {
        if (userInfo) {
            dispatch(getCartListAsync({}))
        }
    }, [dispatch])

    useEffect(() => {



        var flag = cartList.length > 0 && cartList.every((item: any) => item.check)
        setQuan(flag)

        var icount = 0;
        var itotal = 0;
        cartList.forEach((item: any) => {
            if (item.check) {
                icount += item.count;
                itotal += item.count * item.good.price * item.good.discount / 10
            }
        })
        setTotal(itotal)
        setAllCount(icount)


    }, [cartList])
    return (
        <div className='cart'>
            <MyHead title='购物车' back={!!1}></MyHead>
            {
                userInfo ?
                    <div className="cart-box">
                        {
                            cartList.length > 0
                                ?
                                <div className="cart-list">
                                    <List header={'我的购物车商品'}  >
                                        {cartList.map((item: any, index: number) => (
                                            <SwipeAction
                                                key={item._id}

                                                rightActions={[
                                                    {
                                                        key: 'delete',
                                                        text: '删除',
                                                        color: 'danger',
                                                        onClick: async () => {
                                                            await Dialog.confirm({
                                                                content: '确定要删除吗？',
                                                                onConfirm: async () => {

                                                                    let res: any = await Ajax.deletecarts({
                                                                        _id: item._id
                                                                    })
                                                                    if (res.code == 200) {
                                                                        ShowMsg('删除成功')

                                                                        var list = cartList.filter((v: any) => v._id != item._id)

                                                                        dispatch(changeCartList(list))
                                                                    }
                                                                },
                                                            })
                                                        },
                                                    },
                                                ]}
                                            >
                                                <List.Item
                                                    key={index}
                                                    className=" "
                                                    style={{ margin: 10 }}
                                                    arrow={false}
                                                    prefix={
                                                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                                            <Checkbox checked={item.check} onChange={async (check) => {
                                                                let res = await Ajax.updatecarts({
                                                                    _id: item._id,
                                                                    check: check
                                                                }) as any;
                                                                if (res.code == 200) {
                                                                    dispatch(getCartListAsync({}))

                                                                }


                                                            }}></Checkbox>
                                                            <Image
                                                                src={item.good.img}
                                                                style={{ borderRadius: 20 }}
                                                                fit='cover'
                                                                width={240}
                                                                height={240}
                                                                className="ml10"
                                                            />
                                                        </div>
                                                    }
                                                    description={
                                                        <div>
                                                            <div>
                                                                <span>{item.good.type.text} </span>
                                                            </div>
                                                            <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between' }}>
                                                                <span>{item.good.discount}/ 折</span>
                                                                <span>¥ {item.good.price} </span>
                                                            </div>
                                                            <div style={{ marginTop: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                                                <Stepper
                                                                    min={0}
                                                                    value={item.count}
                                                                    onChange={async (val) => {

                                                                        let res = await Ajax.updatecarts({
                                                                            _id: item._id,
                                                                            count: val
                                                                        }) as any;
                                                                        if (res.code == 200) {
                                                                            dispatch(getCartListAsync({}))
                                                                        }

                                                                    }}
                                                                />
                                                                <span>(小计¥) {item.good.price * item.count * item.good.discount / 10} </span>
                                                            </div>
                                                        </div>
                                                    }
                                                >
                                                    <Ellipsis className="name" direction='end' rows={1} content={item.good.name} />
                                                </List.Item>
                                            </SwipeAction>
                                        ))}
                                    </List>
                                </div>
                                :
                                <div>
                                    <Empty
                                        style={{ padding: '64px 0' }}
                                        description='暂无购物车数据,请购买'
                                    />
                                </div>
                        }

                        <div className="cart-foot">
                            <div className="checkall">
                                <Checkbox checked={quan} onChange={async (check) => {
                                    let res = await Ajax.updatecarts({
                                        check
                                    }) as any;
                                    if (res.code == 200) {
                                        dispatch(getCartListAsync({}))
                                    }
                                }}>全选反选</Checkbox>
                            </div>
                            <div className="total">
                                总计: {total}
                            </div>
                            <div>
                                总数量:{allCount}
                            </div>
                            <Button onClick={() => router('/pay?total=' + total)} disabled={!cartList.some((v: any) => v.check)} color="warning" size='mini' className="buybtn mr10" >购买</Button>
                        </div>
                    </div>
                    :
                    <div className="noLoin" style={{ flexDirection: 'column', width: '100%', height: '50vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                        <h3>你尚未登录哦~</h3>
                        <Button color="warning" className='mt10' onClick={() => router('/login')}>请先登录</Button>
                    </div>
            }
        </div>
    )
}

export default Cart